//
//  SearchByStationResultViewController.m
//  ELife
//
//  Created by  刘奇男 on 11-6-9.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "SearchByStationResultViewController.h"
#import "GDataXMLNode.h"
#import "GTMBase64.h"
#import "TrainStation.h"
#import "StationListCellViewController.h"
#import "SearchByLineResultViewController.h"

@implementation SearchByStationResultViewController

@synthesize resultTable;

NSString* startCity;
NSString* endCity;
NSDate* date;

- (void)search
{
    /**
     12.1 火车票站站查询接口
     请求地址: /trainline.php
     请求参数:   
     action    = 'get_trainline_by_station';
     
     begin_station = 起始城市 
     end_station = 抵达城市
     date = 日期 例子:03-15
     
     返回参数: 
     
     train_code  	车次
     start_station   发站
     end_station     到站
     start_time 	发时
     end_time 	到时
     times 		历时
     b_station 始发站
     e_station 终点站
     type 列车类型
     */
    
    NSString* host =  [[NSBundle mainBundle] localizedStringForKey:(@"BussinessHost") value:@"" table:nil];
    NSURL* url = [[NSURL alloc] initWithString:[host stringByAppendingString:@"trainline.php?"]];
    
    NSMutableDictionary *param = [[NSMutableDictionary alloc]initWithCapacity:4];
    [param setObject:@"get_trainline_by_station" forKey:@"action"];
    [param setObject:startCity forKey:@"begin_station"];
    [param setObject:endCity forKey:@"end_station"];
    
    
    NSLog(@"Date-----%@\n", date);
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MM-dd"];
    NSString *stringFromDate = [formatter stringFromDate: date];
    [param setObject:stringFromDate forKey:@"date"];
    [param setObject:[[NSBundle mainBundle] localizedStringForKey:(@"ClientVersion") value:@"" table:nil] forKey:@"version"];
    
    NSDictionary* dic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:url, @"iRequestFinished:", nil] forKeys:[NSArray arrayWithObjects:@"url", @"requestMethod", nil]];
    
    [[app httpRequestPoint]openUrl:dic postParam:param target:self];
}

- (void)iRequestFinished:(NSData *)response
{
    /*
     train_code  	车次
     start_station   发站
     end_station     到站
     start_time 	发时
     end_time 	到时
     times 		历时
     b_station 始发站
     e_station 终点站
     type 列车类型
     */
    [app hideProgressDialog];
    
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[GTMBase64 decodeData:response] options:0 error:nil];
    GDataXMLElement* rootElement = [doc rootElement];    
    
    GDataXMLElement* bodyElement = [[rootElement elementsForName:@"body"]objectAtIndex:0];
    NSLog(@"--------bodyElement:--------\n%@", bodyElement);
    
    //某个具体节点的文本内容
    GDataXMLElement* trainlinesElement = [[bodyElement elementsForName:@"trainlines"]objectAtIndex:0];
    
    NSArray *cityArr = [trainlinesElement children];
    
    result =  [[NSMutableArray alloc] initWithCapacity:[cityArr count]];
    for (int i = 0; i < [cityArr count]; i ++){
        GDataXMLElement *element = [cityArr objectAtIndex:i];
        
        
        NSArray *arr = [element children];
        
        NSString *train_code;//  	车次
        NSString *start_time;// 	发时
        NSString *end_time;// 	到时
        NSString *times;// 		历时
        NSString *b_station;// 始发站
        NSString *e_station;// 终点站
        NSString *type;// 列车类型
        
        for (int j = 0; j<[arr count]; j++) {
            GDataXMLNode *node = [arr objectAtIndex:j];
            
            NSString* key = [node name];
            NSLog(@"--------GDataXMLNode:--------\n%@:%@", key, [node stringValue]);
            if ([key isEqualToString:@"train_code"]){
                train_code = [node stringValue];
            } else if  ([key isEqualToString:@"start_time"]){
                start_time = [node stringValue];                               
            } else if  ([key isEqualToString:@"end_time"]){
                end_time = [node stringValue];                 
            } else if  ([key isEqualToString:@"times"]){
                times = [node stringValue];
            } else if  ([key isEqualToString:@"b_station"]){
                b_station = [node stringValue];                               
            } else if  ([key isEqualToString:@"e_station"]){
                e_station = [node stringValue];                 
            } else if  ([key isEqualToString:@"type"]){
                type = [node stringValue];
            }
        }
        
        TrainStation *trainStation = [[[TrainStation alloc] init] autorelease];
        trainStation.trainCode = train_code;
        trainStation.startTime = start_time;
        trainStation.endTime = end_time;
        trainStation.times = times;
        trainStation.bStation = b_station;
        trainStation.eStation = e_station;
        trainStation.type = type;
        
        [result addObject:trainStation];
    }
    
    NSLog(@"--------result:--------\n%@", result);
    
    [doc release];
    
    [resultTable reloadData];
}

- (void) setQueryParam:(NSString *)start endCity:(NSString*)end date:(NSDate*)d
{
    startCity = start;
    endCity = end;
    date = d;
    
    NSLog(@"Date-----%@\n", date);
}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    app = [ELifeAppDelegate App];
    [app showProgressDialog:@"请稍候"];
    
    [self.resultTable setDelegate:self];
    [self.resultTable setDataSource:self];
    
    [self search];
    
    [self.navigationItem setTitle:@"站站查询"];
}
 
- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	return [result count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *kCellIdentifier = @"SearchByStationCell";

    StationListCellViewController *cell = (StationListCellViewController *)[tableView dequeueReusableCellWithIdentifier:kCellIdentifier]; 
    if (cell == nil) { 
        NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"StationListCellView" owner:self options:nil]; 
        cell = [array objectAtIndex:0]; 
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone]; 
    } 
     
    TrainStation *station = [result objectAtIndex:indexPath.row];
    
    NSInteger num = indexPath.row + 1;
    cell.number.text = [NSString stringWithFormat:@"%i", num];
    cell.trainCode.text = [NSString stringWithFormat:@"%@(%@-%@)", station.trainCode, station.bStation, station.eStation];
    cell.startTime.text = station.startTime;
    cell.endTime.text = station.endTime;
    cell.time.text = station.times;
	
	return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    TrainStation *station = [result objectAtIndex:indexPath.row];
    
    SearchByLineResultViewController *controller = [[SearchByLineResultViewController alloc] initWithNibName:@"SearchByLineResultView" bundle:nil];
    [controller setQueryParam:station.trainCode];
    [self.navigationController pushViewController:controller animated:YES];
    [controller release];
}

- (CGFloat)tableView:(UITableView *)atableView heightForRowAtIndexPath:(NSIndexPath *)indexPath  

{       
    return 90; 
}


@end
